package com.situ.personal.service;

import java.util.List;
import java.util.Map;

import com.situ.personal.dao.UserDao;
import com.situ.personal.dao.UserRoleDao;
import com.situ.personal.entity.PageInfo;
import com.situ.personal.entity.User;
import com.situ.personal.util.MD5Util;


public class UserService {
	private UserDao userDao = new UserDao();
	private UserRoleDao userRoleDao = new UserRoleDao();
	//测试git取消上传；

	public PageInfo findByPage(int pageNo, int pageSize) {
		PageInfo pageInfo = new PageInfo();
		pageInfo.setPageNo(pageNo);
		pageInfo.setPageSize(pageSize);
		
		// totalPage 
		int count = userDao.getTotalCount();
		System.out.println(count);
		int totalPage = (int)Math.ceil((double)count / pageSize);
		pageInfo.setTotalPage(totalPage);
		System.out.println(totalPage);
		
		// list
		// pageNo,pageSize-->limit (pageNo-1)*pageSize,pageSize
		int offset = (pageNo - 1) * pageSize;
		//List<User> list = userDao.findByPage(offset, pageSize);
		List<Map<String, Object>> list = userDao.findByPage3(offset, pageSize);
		pageInfo.setList(list);
		
		return pageInfo;
	}

	public boolean update(User user) {
		int count = userDao.update(user);
		if (count == 1) {
			return true;
		} else {
			return false;
		}
	}

	public User selectById(int id) {
		User user = userDao.selectById(id);
		return user;
	}

	public boolean insert(User user) {
		String encodePassword = MD5Util.EncodeUtf8(user.getPassword());
		user.setPassword(encodePassword);
		int count = userDao.insert(user);
		if (count == 1) {
			return true;
		} else {
			return false;
		}
	}

	public boolean deleteById(int id) {
		// 直接去user表根据id删除这个用户，可能会报错：Cannot delete or update a parent row: a foreign key constraint fails
		// 问题就是user_role表里面有外键约束，在user表删除用户，但是在user_role表还
		// 保存这个用户的角色信息，就会报错
				
		// Service层是业务逻辑层，逻辑代码应该写到这一层
		// 1、先去user_role表删除这个用户下面所有的角色delete from user_role where user_id=6;
		// 2、再去user表删除这个用户 delete from user where id=6;
		userRoleDao.deleteByUserId(id);
		int count = userDao.deleteById(id);
		if (count == 1) {
			return true;
		} else {
			return false;
		}
		
	}

	public List<User> findAll() {
		List<User> list = userDao.findAll();
		return list;
	}
	public User login(String name, String password) {
		return userDao.login(name, MD5Util.EncodeUtf8(password));
	}
	

	
}
